package com.example.screenprojection;

import android.Manifest;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

  private static final int PROJECTION_REQUEST_CODE = 1;

  private MediaProjectionManager mediaProjectionManager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    init();
  }

  private void init() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(new String[]{/*Manifest.permission.ACCESS_FINE_LOCATION, */Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
    }

  }

  public void onClick(View view) {
    int id = view.getId();
    if (id == R.id.btn_start) {
        startProjection();
    }
  }

  @Override
  protected void onResume() {
    super.onResume();
  }

  @Override
  protected void onPause() {
    super.onPause();
  }

  // 请求开始录屏
  private void startProjection() {
      Intent intent = null;
      if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        intent = mediaProjectionManager.createScreenCaptureIntent();
        startActivityForResult(intent, PROJECTION_REQUEST_CODE);
      }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_OK) {
      return;
    }
    if (requestCode == PROJECTION_REQUEST_CODE) {
      Intent service = new Intent(this, ScreenService.class);
      service.putExtra("code", resultCode);
      service.putExtra("data", data);
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(service);
      } else {
        startService(service);
      }
    }
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
  }
}
